/**
 * Created by DevilsEyes on 2016/3/14.
 */
'use strict';

define(['text!path/cart/tmp.html', 'logger', 'layer'], function (page, logger, layer) {

    var render = template.compile(page);
    var symbol = {};

    var apiList = {
        getCartInfo: api + 'cart/list',
        delete: api + 'cart/remove',
        confirm: api + 'order/check',
        add: api + 'cart/plus',
        desc: api + 'cart/minus',
        set: api + 'cart/set'
    };
    console.log(layer);

    var vm = new Page.creat({
        $id: 'cart',
        $model: {
            data: {},
            $: {},
            init: function () {

                //$.ajax({
                //    url: '../testData/homepage.json',
                ex.jsonp({
                    url: apiList.getCartInfo,
                    success: function (obj) {
                        if (!vm.isThisPage())return;
                        console.log(obj);

                        obj = obj.data;
                        obj.list = $.map(obj.list, function (v) {
                            return $.extend(v, {
                                check: true
                            });
                        });

                        vm.data = {
                            skus: obj.list,
                            amount: 0,
                            freeLine: obj.man
                        };

                        $('#page').html(render(vm.data));

                        ex.async(function () {

                            vm.bindEvent(vm.event);
                            vm.bind$(vm.$);
                            vm.action.checkAmount();

                        });
                    }
                })
            },
            event: {
                topbtnClick: function () {
                    var $allSlider = $('.tumb-slider');
                    var $allDelete = $('.deleteArea');
                    var $this = $(this);

                    if (symbol.edit) {
                        symbol.edit = false;
                        $this.text('编辑');
                        $allSlider.css('left', 0);
                        $allDelete.css('right', -60);
                    } else {
                        symbol.edit = true;
                        $this.text('完成');
                        $allSlider.css('left', -60);
                        $allDelete.css('right', 0);

                    }
                },
                descCount: function (index) {
                    var thisSku = vm.data.skus[index];
                    thisSku.quantity--;
                    if (vm.action.checkQuality(index)) {
                        ex.jsonp({
                            url: apiList.desc,
                            method: 'POST',
                            data: {
                                sku_id: thisSku._id
                            },
                            success: function () {

                            }
                        });
                    }
                },
                addCount: function (index) {
                    var thisSku = vm.data.skus[index];
                    thisSku.quantity++;
                    if (vm.action.checkQuality(index)) {
                        ex.jsonp({
                            url: apiList.add,
                            method: 'POST',
                            data: {
                                sku_id: thisSku._id
                            },
                            success: function () {

                            }
                        });
                    }
                },
                setCount: function (index) {
                    var thisSku = vm.data.skus[index];
                    thisSku.quantity = +$(this).val();
                    var setNum = vm.action.checkQuality(index);
                    if (setNum) {
                        ex.jsonp({
                            url: apiList.set,
                            method: 'POST',
                            data: {
                                sku_id: thisSku._id,
                                quantity: setNum
                            },
                            success: function () {

                            }
                        });
                    }
                },
                checkboxClick: function (index) {
                    var thisSku = vm.data.skus[index];
                    thisSku.check = !thisSku.check;
                    $(this).find('.checkbox').attr('data-check', thisSku.check);
                    vm.action.checkAmount();
                    vm.action.checkAllSelect();
                },
                selectAll: function () {
                    symbol.selectAll = !symbol.selectAll;
                    for (var i = 0; i < vm.data.skus.length; i++) {
                        if (vm.data.skus[i]) {
                            vm.data.skus[i].check = symbol.selectAll;
                        }
                    }
                    $('.checkbox').attr('data-check', symbol.selectAll);
                    vm.action.checkAmount();
                },
                deleteSKU: function (index) {
                    var thisSku = vm.data.skus[index];
                    ex.jsonp({
                        url: apiList.delete,
                        method: "POST",
                        data: {
                            sku_infos: [thisSku._id]
                        },
                        success: function (res) {
                            if (!vm.isThisPage())return;
                            if (res.code != 0)return layer.msg(res.msg);
                            vm.data.skus[index] = null;
                            vm.$['product-' + index].remove();
                            vm.action.checkAmount();
                        }
                    })
                },
                clickfb: function () {
                    if (vm.$.fbutton.hasClass('un') || symbol.confirmPending)return;
                    symbol.confirmPending = true;
                    var SKUs = {};
                    for (var i = 0; i < vm.data.skus.length; i++) {
                        if (vm.data.skus[i] != null && vm.data.skus[i].check) {
                            SKUs[vm.data.skus[i]._id] = vm.data.skus[i].quantity;
                        }
                    }
                    ex.jsonp({
                        url: apiList.confirm,
                        method: "POST",
                        data: {
                            skus: SKUs
                        },
                        success: function (res) {
                            if (!vm.isThisPage())return;
                            console.log(res);
                            symbol.confirmPending = false;
                            if (res.code != 0) {
                                return layer.msg(res.msg);
                            } else {
                                //todo 确认下单流程
                                db.set('confirmOrder', res.data);
                                console.log(db);
                                location.hash = '/confirmOrder'
                            }
                        },
                        error: function () {
                            symbol.confirmPending = false;
                            layer.msg('网络连接好像不太顺畅哦');
                        }
                    })
                }
            },
            action: {
                checkQuality: function (index) {
                    var pass = true;
                    var thisSku = vm.data.skus[index];
                    if (thisSku.quantity > thisSku.stock) {
                        thisSku.quantity = thisSku.stock;
                        pass = false;
                    }
                    if (thisSku.quantity <= 0) {
                        thisSku.quantity = 1;
                        pass = false;
                    }
                    vm.$['count-' + index].val(thisSku.quantity);
                    vm.action.checkAmount();
                    if (pass) {
                        return thisSku.quantity;
                    } else {
                        return false;
                    }
                },
                checkAmount: function () {
                    var amount = 0;
                    $.map(vm.data.skus, function (v) {
                        if (v && v.check) {
                            amount += v.quantity * v.price;
                        }
                    });
                    vm.data.amount = amount;
                    //同步视图
                    if (amount > 0) {
                        vm.$.fbutton.removeClass('un');
                    } else {
                        vm.$.fbutton.addClass('un');
                    }
                    if (amount < vm.data.freeLine) {
                        vm.$.freeRemain.html('还差<b>' + (vm.data.freeLine - amount) / 10 + '元</b>包邮');
                    } else {
                        vm.$.freeRemain.html('<b>已包邮</b>');
                    }
                    vm.$.amount.text(amount / 10);
                },
                checkAllSelect: function () {
                    var check = true;
                    for (var i = 0; i < vm.data.skus.length; i++) {
                        if (vm.data.skus[i] && !vm.data.skus[i].check) {
                            check = false;
                            symbol.selectAll = true;
                            break;
                        }
                    }
                    vm.$.selectAll.find('.checkbox').attr('data-check', check);
                }
            }
        }
    });

    return {
        init: function () {
            vm.$init({
                setTitle: '购物车'
            });

            vm.init();
        }
    }
});